package com.example.testdemo.scrollDelete;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

/**
 * Created by MrYan on 2018/8/24.
 * 侧滑删除
 */

public class ScrollDeleteView extends LinearLayout {

    private View viewLeft;
    private View viewRight;
    public ScrollDeleteView(Context context) {
        super(context);
    }

    public ScrollDeleteView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ScrollDeleteView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        viewLeft = getChildAt(0);
        viewRight = getChildAt(1);
        viewLeft.layout(0,0,getMeasuredWidth(),getBottom());
        viewRight.layout(viewRight.getLeft(),0,viewRight.getLeft() + getMeasuredWidth(),getBottom());
    }

    private float downX;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (downX - event.getX() > viewRight.getWidth()){
                    scrollTo(viewRight.getWidth(),0);
                }else {
                    scrollTo(0,0);
                }
                break;
            case MotionEvent.ACTION_MOVE:

                if (downX - event.getX() > 20){
                    scrollTo((int) (downX - event.getX()),0);
                }
                break;
        }
        return true;
    }
}
